package com.xiong.wuliao;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.xiong.wuliao.adapter.MyHomeListAdapter;
import com.xiong.wuliao.entity.HomeStorys;
import com.xiong.wuliao.util.HomeJSON;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 分类页面的专栏点击后的“专栏页面”
 */
public class ColumnActivity extends AppCompatActivity implements View.OnClickListener {
    //http://api.wuliaoribao.com/v2/channels/16/items?gender=2&limit=20&offset=0&generation=2
    // 故事列表地址前段
    private String storyPath = "http://api.wuliaoribao.com/v2/channels/";
    // 故事id
    private String storyId;
    // 故事名称
    private String storyName;

    private SwipeRefreshLayout mySwipeRefreshLayoutColumn;
    private ListView myListViewColumn;

    //**********这里和首页中的ListView是一样的，所以采用一样的数据结构**************
    // 刷新后请求服务器的参数
    private int offset = 0;
    // 是否到达页面底部的标注
    private boolean isBottom = false;
    // 保存服务器传过来的数据
    private List<HomeStorys> storysList = new ArrayList<>();
    // ListView的自定义适配器
    private MyHomeListAdapter adapter;

    // 返回图片按钮
    private ImageButton myButtonColumn;
    // 专栏标题
    private TextView myTextViewColumn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_column);

        init();
    }

    private void init() {
        findView();
        getStoryId();
        initData();
        setMyAdapter();
        setListener();
    }

    /**
     * 设置适配器
     */
    private void setMyAdapter() {
        adapter = new MyHomeListAdapter(ColumnActivity.this, storysList);
        myListViewColumn.setAdapter(adapter);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        getZhuanLanServerData();
    }

    /**
     * 获得传过来的Id
     */
    private void getStoryId() {
        Intent intent = getIntent();
        storyId = intent.getStringExtra("storyId") + "/items";
        storyName = intent.getStringExtra("storyName");

        // 设置专栏标题
        myTextViewColumn.setText(storyName);

    }

    /**
     * 设置监听事件
     */
    private void setListener() {
        /**
         * 返回的监听
         */
        myButtonColumn.setOnClickListener(this);

        /**
         * 上拉加载的监听
         */
        myListViewColumn.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (isBottom && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    offset += 20;
                    getZhuanLanServerData();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                isBottom = firstVisibleItem + visibleItemCount == totalItemCount;
            }
        });

        /**
         * 下拉刷新的监听
         */
        mySwipeRefreshLayoutColumn.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                offset += 20;
                getZhuanLanServerData();

            }
        });

        /**
         * ListView的item点击事件
         */
        myListViewColumn.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HomeStorys storys = storysList.get(position);
                String lastId = storys.getId();
                Intent intent = new Intent(ColumnActivity.this, SpecialActivity.class);
                intent.putExtra("lastId", lastId);
                startActivity(intent);
            }
        });
    }

    /**
     * 保存服务器数据
     */
    private void getZhuanLanServerData() {
        String string = storyPath + storyId;   //gender=2&limit=20&offset=0&generation=2
        OkHttpUtils.get(string)
                .params("gender", 2)
                .params("limit", 20)
                .params("offset", offset)
                .params("generation", 2)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(s.trim());
                            String result = jsonObject.getString("message");
                            if (result.equals("OK")) {

                                storysList.addAll(HomeJSON.saveHomeStory(s.trim()));
                                adapter.notifyDataSetChanged();
                            } else {
                                Toast.makeText(ColumnActivity.this, "数据请求失败", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    /**
     * 初始化控件
     */
    private void findView() {
        myButtonColumn = (ImageButton) findViewById(R.id.myButtonColumn);
        myTextViewColumn = (TextView) findViewById(R.id.myTextViewColumn);

        mySwipeRefreshLayoutColumn = (SwipeRefreshLayout) findViewById(R.id.mySwipeRefreshLayoutColumn);
        myListViewColumn = (ListView) findViewById(R.id.myListViewColumn);
    }

    /**
     * 普通点击监听事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.myButtonColumn:    // 点击了返回图标
                ColumnActivity.this.finish();
                break;
        }
    }
}
